package thread.threadlocal;

import java.util.concurrent.*;

/**
 * @Author: ycy
 * @CreateDate: 2019/10/10 12:17
 */
public class ThreadLocalDemo {

  //声明一个线程池
//  private static ExecutorService es = Executors.newFixedThreadPool(5);

  private final static int max = 5;

  private final static ThreadLocal<Size> threadLocal = new ThreadLocal<Size>();

  public static void main(String[] args) {
    LinkedBlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
    ExecutorService es = new ThreadPoolExecutor(5, 5,
            0L, TimeUnit.MILLISECONDS,
            linkedBlockingQueue);

    while (true) {
      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      if (linkedBlockingQueue.size() > max) {
        System.out.println("continue");
        continue;
      }

      Thread thread1 = new Thread() {
        @Override
        public void run() {
          System.out.println(Thread.currentThread().getName() + " 开始执行任务");
//          new Size();
          threadLocal.set(new Size()); //这个可能会内存泄漏
          try {
            Thread.sleep(20000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " 结束任务了");
        }
      };

      es.execute(thread1);
    }

  }

  static class Size {
    public byte[] m = new byte[1024 * 1024 * 5];
  }

}


